# -*- coding: utf-8 -*-
"""
Created on Tue Jun 07 09:43:38 2016

@author: houruquan
"""
from subprocess import Popen, PIPE, call
import time
import re
import os, datetime
import pdb


def svnbak(proname, bakpath, svnpath):
    dnow = datetime.datetime.now()
    date = dnow.strftime("%Y-%m-%d")
    date2 = dnow - datetime.timedelta(days=21)  # 20天之前的时间
    date2re = date2.strftime("%Y-%m-%d")
    logdate = dnow.strftime("%Y-%m-%d_%H::%M")
    try:
        directory = os.listdir(str(bakpath) + str(proname))
    except WindowsError, e:
        print "THis is no this directory", e
        return
        # os.mkdir(str(bakpath)+str(proname))
    filename = "weeklybakcup" + str(proname) + str(date) + ".bak"
    print filename
    p = Popen(['svnlook', 'youngest', str(svnpath) + str(proname)], \
              shell=True, stdout=PIPE)  # 记得加入shell=True,stdout=PIPE
    a = p.communicate()[0].strip()  # 返回一个标准输出，标准错误的元组,并取出标准输出
    if os.path.exists(str(bakpath) + str(proname) + "/" + "weeklylastest.log"):  # os.path.exists判断日志文件是否存在
        b = open(str(bakpath) + str(proname) + "/" + "weeklylastest.log", 'r')  # 如果存在，进行赋值
        b = b.read()
        print b
    # pdb.set_trace()     调试的时候使用
    else:
        b = 0
    fullbakpath = str(bakpath) + str(proname) + "/" + str(filename)
    print fullbakpath
    if b != a:
        call(['svnadmin', 'dump', '-r', '0:%s' % a, str(svnpath) + str(proname), '>',
              str(bakpath) + str(proname) + "/" + str(filename)], shell=True)
        f = file(str(bakpath) + str(proname) + "/" + "weeklylastest.log", 'w')  # 如果版本号不一致就进行全量备份
        f.write(a)
        f.close()
        log = file(str(bakpath) + str(proname) + "/" + "log_dump", 'a+')
        log.write(
            "\n%s is a full dumpfile for project %s at %s,the Number is 0 to %s " % (filename, proname, logdate, a))
        log.close()
    else:
        pass


def weeklybakdel(proname, bakpath, svnpath):
    dnow = datetime.datetime.now()
    logdate = dnow.strftime("%Y-%m-%d_%H::%M")
    try:
        directory = os.listdir(str(bakpath) + str(proname))
    except WindowsError, e:
        print "proname is wrong,this is no this directory", e
        return
    listfile = []
    for filebak in directory:
        # 文件中是否含有weekly日期格式,如果有把文件放入到listfile
        if re.search("^weekly.*\d+", filebak):
            riqi = filebak[-14:-4]
            listfile.append(str(riqi))  # 将日期加入到列表
        else:
            pass

    print "listfile is %s" % listfile
    while len(listfile) > 5:  # 判断有几个全量备份 如果大于5个备份开始DEL最早的备份
        earlydate = time.strptime(listfile[0], '%Y-%m-%d')  # 初始化一个最早备份日期
        for j in range(len(listfile)):

            filedate = time.strptime(listfile[j], "%Y-%m-%d")
            if filedate < earlydate:
                earlydate = filedate
            else:
                pass
        print "earlydate is %s" % earlydate
        earlyre = time.strftime("%Y-%m-%d", earlydate)
        print "earlyre is %s" % earlyre


        listfile.remove(earlyre)
        print listfile
        for filebak in directory:
            an = re.search(earlyre, filebak)
            if an:
                os.remove(str(bakpath) + str(proname) + "/" + str(filebak))  # 匹配20天以前的数据，删去。此匹配必须要备份成功以后才执行。
                logr = file(bakpath + proname + "/" + "log_dump", 'a+')
                logr.write("\n************The weekly dumpfile %s was remove at %s" % (filebak, logdate))
            else:
                pass

        # 匹配最早日期,删

svnpath = "D:/VISUAL_SVN/"
bakpath = "f:/svnbak/"
projectfile = open("F:/PYTHON/project_peizhi/project_weekly1.txt")
for line in projectfile.readlines():
    line = line.strip('\n')
    print line
    if line != "":
        svnbak(line, bakpath, svnpath)
        weeklybakdel(line, bakpath, svnpath)
    else:
        pass
    
dnow = datetime.datetime.now()
date = dnow.strftime("%Y-%m-%d HH:MM")
logall=file("F:/svnbak/backup_log.txt",'a+')
logall.write("\nsucess backup weekly1 daily at %s"%date)
logall.close()
